package com.gl.organigrama.repository.jpa;

import java.util.List;

import javax.persistence.Entity;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.springframework.stereotype.Repository;

import com.gl.organigrama.repository.INodoRepository;
import com.gl.organigrama.vos.IValorObjeto;
import com.gl.organigrama.vos.Nodo;

@Repository
public class JpaNodoRepository implements INodoRepository{
	
	@PersistenceContext
	private EntityManager em;
	
	@Override
	public Nodo save(Nodo nodo) {
		Nodo merge = em.merge(nodo);
		((IValorObjeto)nodo).setId(merge.getId());
		return merge;
	}
	
	@Override
	public void remove(Nodo nodo){
		Object e = (Object) em.find(Nodo.class, nodo.getId());
		em.remove(e);
	}
	
	@Override
	public Nodo find(Long id){
		Nodo nodo = em.find(Nodo.class, id);
		return nodo;
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public List<Nodo> findNodos(){
		Query query = null;
		String ejbql = "FROM Nodo";
		try {
			query = em.createQuery(ejbql );
			return query.getResultList();
		} catch (Exception e) {
			throw new RuntimeException(String.format("Error al ejecutar la query '%s'", ejbql), e);
		}
	}
	
	@Override
	public Nodo getNodoPadre() throws Exception {
		Query query = null;
		try {
			query = em.createQuery("FROM Nodo as nodo WHERE nodo.esNodoBase = true");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return (Nodo)query.getSingleResult();
	}

	@Override
	public List<Nodo> recuperarHijosNivelUno(Long idNodo){
		Query query = null;
		try {
			query = em.createQuery("SELECT nodo.hijosNivelUno FROM Nodo as nodo WHERE nodo.id = :param");
			query.setParameter("param", idNodo);
		} catch (Exception e) {
			e.printStackTrace();
		}
		if(query.getResultList() != null){
			return query.getResultList();
		}
		return null;
	}

	@Override
	public List<Nodo> recuperarHijosNivelDos(Long idNodo){
		Query query = null;
		try {
			query = em.createQuery("SELECT nodo.hijosNivelDos FROM Nodo as nodo WHERE nodo.id = :param");
			query.setParameter("param", idNodo);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return query.getResultList();
	}
	
	@Override
	public Nodo getNodoPadre(Nodo nodo) {
		Query query = null;
		try{
			query = em.createQuery("SELECT nodo FROM Nodo nodo WHERE :param MEMBER OF nodo.hijosNivelUno");
			query.setParameter("param", nodo);
		}catch (Exception e) {
			e.printStackTrace();
		}
		return (Nodo)query.getSingleResult();
		
	}
}
